package com.oocl.o2o.client.dao.impl;

import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.TypedQuery;
import org.springframework.stereotype.Repository;
import com.oocl.o2o.client.dao.MerchantDao;
import com.oocl.o2o.client.entity.Merchant;


@Repository(value="merchantDaoImpl")
public class MerchantDaoImpl implements MerchantDao {

	@PersistenceContext(name="un")
	private EntityManager em;
	@Override
	public Merchant add(Merchant t) {
		em.persist(t);
		return t;
	}

	@Override
	public Merchant update(Merchant t) {
		String id = t.getId();
		String username = t.getUsername();
		String password = t.getPassword();
		String idCard = t.getIdCard();
		String portrait = t.getPortrait();
		String address = t.getAddress();
		Merchant merchantInDb = em.find(Merchant.class, id);
		merchantInDb.setUsername(username);
		merchantInDb.setPassword(password);
		merchantInDb.setIdCard(idCard);
		merchantInDb.setPortrait(portrait);
		merchantInDb.setAddress(address);
		return merchantInDb;
	}

	@Override
	public Merchant delete(String id) {
		Merchant merchantInDb = em.find(Merchant.class, id);
		em.remove(merchantInDb);
		return merchantInDb;
	}

	@Override
	public Merchant findById(String id) {
		Merchant merchantInDb = em.find(Merchant.class, id);
		return merchantInDb;
	}

	@Override
	public List<Merchant> findAll() {
		String jpql = "select m from Merchant m";
		TypedQuery<Merchant> query = em.createQuery(jpql, Merchant.class);
		List<Merchant> merchants = query.getResultList();
		return merchants;
	}

	@Override
	public Merchant findByUsername(String username) {
		String jpql = "select m from Merchant m where m.username = :username";
		TypedQuery<Merchant> query = em.createQuery(jpql, Merchant.class);
		Merchant merchant = null;
		try {
			// if find nothing, it throw exception
			merchant = query.setParameter("username", username).getSingleResult();
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
		return merchant;
	}

}
